<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总共: {{ total }}条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/employees/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="dialogemployees=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px;">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <!-- <img class="avatar" :src="row.staffPhoto" alt=""> -->
              <Imagehead :src="row.staffPhoto"/>
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template v-slot="{row}">
              <!-- {{ row.formOfEmployment===1?'正式':'非正式' }} -->
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row}">
              {{ formatDate(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hassign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            background
            :current-page="q.page"
            :page-size="q.size"
            :page-sizes="[2,3, 5, 10]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        v-if="dialogemployees"
        title="新增员工"
        :visible.sync="dialogemployees"
        width="40%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <EmpDialog @close="dialogemployees=false" @success="hSuccess" />
      </el-dialog>
            <el-dialog
        title="分配角色"
        :visible.sync="dialogemployeesupdate"
        width="50%"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
      <!-- roleIds 数据回填 -->
    <el-checkbox-group v-model="roleIds">
    <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
  </el-checkbox-group>
      <div style="text-align: right">
    <el-button type="primary" @click="hSubimit">确 定</el-button>
    <el-button @click="dialogemployeesupdate = false">取 消</el-button>
    </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import employeesConst from '@/constant/employees'
import { getEmployeeList, DelEmployees, AssignEmployee } from '@/api/employees'
import EmpDialog from './empDialog.vue'
import dayjs from 'dayjs'
import { getroles } from '@/api/roles'
import { getUserDetailById } from '@/api/user'
const hireTypeMap = {}
// 执行循环后达成目标
employeesConst.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    EmpDialog
  },
  data() {
    return {
      employees: [],
      q: {
        page: 1,
        size: 10
      },
      total: 0,
      dialogemployees: false,
      dialogemployeesupdate:false,
      roleIds: [],
      roles:[],
      id:''
    }
  },
  created() {
    this.loadEmployeeList()
    this.loadRoles()
    // this.loadRoleIds()
  },
  methods: {
    async  loadEmployeeList() {
      const res = await getEmployeeList(this.q)
      console.log('员工列表', res.data)
      this.employees = res.data.rows
      console.log('数量', res.data.rows)
      this.total = res.data.total
    },
    formatEmployment(code) {
      return hireTypeMap[code]
    },
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployeeList()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployeeList()
    },
    // 删除员工
    async  hDel(id) {
      await this.$confirm('确定要删除吗?', '提示', { type: 'warning' })
      try {
        const res = await DelEmployees(id)
        console.log('删除员工', res)
        this.$message.success(res.message)
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployeeList()
      } catch (e) {
        if (e === 'cancel') return
        this.$message.error(e.message)
      }
    },
    hSuccess() {
      this.dialogemployees = false
      // 判断最后一页是否满了
      if (this.total % this.q.size === 0) {
        this.total++
      }
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployeeList()
    },
    formatDate(data) {
      return dayjs(data).format('YYYY-MM-DD')
    },
    // 导出文件
    async  hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const res = await getEmployeeList({ page: 1, size: this.total })
      console.log('请求数据', res)
      // 取第一个数据
      const list = res.data.rows
      // 遍历list将每个属性名转换成英文
      const zhList = list.map(enobj => {
        const zhobj = {}
        const enKeys = Object.keys(enobj)
        enKeys.forEach(enKey => {
          const zhKey = mapInfo[enKey]
          zhobj[zhKey] = enobj[enKey]
        })
        return zhobj
      })
      const first = zhList[0]
      if (!first) return
      const header = Object.keys(first)
      const data = zhList.map(item => {
        return Object.values(item)
      })
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header,
        data,
        filename: '学习资料', // 文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })
    },
   async  hassign(id){
     //角色信息数据回填
     this.id=id
      this.dialogemployeesupdate=true
    const res = await getUserDetailById(id)
    console.log('角色信息',res.data);
    this.roleIds=res.data.roleIds
    },
   async  loadRoles(){
    //角色名称
    const res = await  getroles(this.q)
    console.log('角色名称',res.data.rows);
    this.roles=res.data.rows
    },
  async  hSubimit(){
    try{
          const res = await  AssignEmployee({
          id: this.id,
          roleIds: this.roleIds
        })
        this.$message.success(res.message)
        console.log('分配权限',res.data);
    }catch(e){
      this.$message.error(e.message)
    }
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination{
  height: 60px;
  display: flex;
  justify-content: center;
  align-content: center;
}
</style>
